package listener;

import emailTransfer.SendEmail;
import fileIO.WriteTxTFile;
import guiParts.EmailSendGui;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.border.BevelBorder;
import javax.swing.border.Border;
import javax.swing.filechooser.FileFilter;

import panelSites.ContentPanel;
import panelSites.PanelSitesIface;
import panelSites.SendedEmailPanel;
import panelSites.SendingPanel;
import panelSites.StatusPanel;
import panelSites.SubjectPanel;
import propertiesReader.PropertiesReader;
import xls.ReadXLS;

public class ButtonActionListener implements ActionListener {

	private EmailSendGui view;

	private SendEmail sendMail;

	private Thread myThread;

	private boolean endproductrdy;
	
	private WriteTxTFile txtwriter = new WriteTxTFile();

	private Border border = BorderFactory
			.createBevelBorder(BevelBorder.LOWERED);
	private Border noBorder = BorderFactory
			.createBevelBorder(BevelBorder.RAISED);

	private List<JButton> registrierteButtons = new LinkedList<JButton>();
	private PropertiesReader pReader;
	
	//Gui-Sites for the centerPanel
	private SubjectPanel subjectPanel;
	private ContentPanel contentPanel;
	private StatusPanel statusPanel;
	private SendedEmailPanel sendedEmailPanel;
	private SendingPanel sendP;
	
	//List with the Panels
	List<PanelSitesIface> panels;
	

	public void registerButton(JButton button) {
		registrierteButtons.add(button);
	}
	
	private void setBorder(JButton button) {

		for (JButton buttonInList : registrierteButtons) {
			if (button.equals(buttonInList)) {
				buttonInList.setBorder(border);
			} else {
				buttonInList.setBorder(noBorder);
			}
		}

		view.repaint();
		view.setVisible(true);
	}

	private void removeBorder() {
		for (JButton buttonInList : registrierteButtons) {
			buttonInList.setBorder(noBorder);
		}
		view.repaint();
		view.setVisible(true);
	}

	public ButtonActionListener(EmailSendGui front, boolean end) {
		endproductrdy = end;
		//sendMail = model;
		pReader = new PropertiesReader(end);
		this.view = front;
		
		
		//Panels
		subjectPanel = new SubjectPanel(view.getTmpBetreff());
		contentPanel = new ContentPanel(view.getTmpContent());
		statusPanel = new StatusPanel(view);
		sendedEmailPanel = new SendedEmailPanel(endproductrdy);
		sendP = new SendingPanel(view);
		
		panels = new LinkedList<PanelSitesIface>();
		panels.add(subjectPanel);
		panels.add(contentPanel);
		panels.add(statusPanel);
		panels.add(sendedEmailPanel);
	}

	public void actionPerformed(ActionEvent e) {
		JButton sourceButton = (JButton) e.getSource();
		setBorder(sourceButton);
		view.centerPanel.removeAll();
		view.centerPanel.setBackground(Color.LIGHT_GRAY);
		if (sourceButton.equals(view.getBetreff())) {
			betreffAction();
			actualize();
		} else if (sourceButton.equals(view.getTextButton())) {
			inhaltAction();
			actualize();
		} else if (sourceButton.equals(view.getAnhang())) {
			attachmentAction();
			actualize();
		} else if (sourceButton.equals(view.getXls())) {
			xlsAction();
			actualize();
		} else if (sourceButton.equals(view.getSave())) {
			saveAction();
			actualize();
		} else if (sourceButton.equals(view.getReset())) {
			try {
				resetAction();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		} else if (sourceButton.equals(view.getSend())) {
			sendAction();
			actualize();
		} else if (sourceButton.equals(view.getStatus())) {
			statusAction();
			actualize();
		} else if (sourceButton.equals(view.getStop())) {
			stopAction();
			actualize();
		} else if (sourceButton.equals(view.getSendedEmails())) {
			showEmailsAction();
			actualize();
		} else if(sourceButton.equals(view.getSendingStatus())) {
			processAction();
			actualize();
		}
		view.centerPanel.setBackground(view.backGroundColorCenter);
		view.repaint();
		view.setVisible(true);
	}

	private void betreffAction() {
		subjectPanel.setText(view.getTmpBetreff());
		subjectPanel.repaint();
		view.centerPanel.add(subjectPanel);
	}

	private void inhaltAction() {
		contentPanel.setText(view.getTmpContent());
		view.centerPanel.add(contentPanel);
	}

	private void statusAction() {
		statusPanel.setText("");
		view.centerPanel.add(statusPanel);
	}

	private void resetAction() throws IOException {
		view.readTxtFiles();
		view.centerPanel.setBackground(view.backGroundColorCenter);
		removeBorder();
	}

	private void printInfos() {
		System.out.println("Anhangspfad tmp <- Aktuell: "
				+ view.getTmpAttachmentPath());
		System.out.println("Anhangspfad prop: "
				+ pReader.getProperty("attachmentPath"));
		System.out.println("XLSpfad tmp: <- Aktuell" + view.getTmpXlsPath());
		System.out.println("XLSpfad prop: " + pReader.getProperty("xlsPath"));
	}

	private void sendAction() {
		sendP.repaint();
		view.centerPanel.add(sendP);
		
		view.centerPanel.repaint();
		
		//Get Checkboxes
		boolean typeHtml = statusPanel.getHtmlCheckBox();
		boolean attach = statusPanel.getAttachmentCheckBox();
		
		//Actualize Emails
		ReadXLS readXls = ReadXLS.getInstance();
		view.setEmailAdresses(readXls.readXLS(pReader.getProperty("xlsPath")));
		
		try {
			sendMail = SendEmail.getInstance(view, sendP, endproductrdy, view.getTmpBetreff(),
					view.getTmpContent(), view.getTmpAttachmentPath(), view.getEmailAdresses(), typeHtml, attach);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		printInfos();

		myThread = new Thread(sendMail);
		myThread.start();
		view.getStop().setEnabled(true);
		view.getSend().setEnabled(false);
		sendMail.setRun(true);
		view.getSendingStatus().setEnabled(true);
		view.getSendingStatus().setVisible(true);
		view.getStop().setEnabled(true);

		view.repaint();
		
	}
	
	private void processAction(){
		sendP.repaint();
		view.centerPanel.add(sendP);
	}

	private void stopAction() {
		sendMail.setRun(false);
		sendMail.serialize();
		view.getStop().setEnabled(false);
		view.getSendingStatus().setEnabled(false);
		view.getSendingStatus().setVisible(false);
		view.getSend().setEnabled(true);
		
		removeBorder();
	}

	/**
	 * Get the actual texts from the ui. If there is a reset, this should be deactivated
	 */
	private void actualize() {
		view.setTmpBetreff(subjectPanel.getText(), "actualize");
		view.setTmpContent(contentPanel.getText());
	}

	private void attachmentAction() {
		JFileChooser fc = new JFileChooser();
		File file = new File("");
		int returnVal = fc.showOpenDialog(null);
		;
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			file = fc.getSelectedFile();
			// This is where a real application would open the file.
			view.setTmpAttachmentPath(file.getAbsolutePath());
		} else {
			System.err.println("Operation abgebrochen");
		}
	}

	private void saveAction() {
		System.out.println("Properties stored: ");
		System.out.println(view.getTmpAttachmentPath());

		// Save Textfiles

		pReader.store(view.getTmpAttachmentPath(), view.getTmpXlsPath());

		// Set txt files
		txtwriter.writeFile(subjectPanel.getText(),
				pReader.getProperty("subjectPath"));
		txtwriter.writeFile(contentPanel.getText(),
				pReader.getProperty("newsTextPath"));

	}

	private void showEmailsAction() {
		SendedEmailPanel sendedEmailPanel = new SendedEmailPanel(endproductrdy);
		view.centerPanel.add(sendedEmailPanel);
	}

	private void xlsAction() {
		JFileChooser fc = new JFileChooser();
		FileFilter ff = new FileFilter() {

			@Override
			public String getDescription() {
				return ".xls";
			}

			@Override
			public boolean accept(File f) {
				if (f.getName().endsWith(".xls")) {
					return true;
				} else if (f.isDirectory()) {
					return true;
				}
				return false;
			}
		};
		fc.setFileFilter(ff);
		File file = new File("");
		int returnVal = fc.showOpenDialog(null);
		;
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			file = fc.getSelectedFile();
			// This is where a real application would open the file.
			// Set the new path
			view.setTmpXlsPath(file.getAbsolutePath());
			ReadXLS readxls = ReadXLS.getInstance();
			// Actualize the email-adresses
			view.setEmailAdresses(readxls.readXLS(file.getAbsolutePath()));
		} else {
			System.err.println("Operation abgebrochen");
		}
	}
}
